package com.asimplefox.controllers;

import com.asimplefox.entity.Tag2name;
import com.asimplefox.entity.Tags;
import com.asimplefox.entity.VidList;
import com.asimplefox.service.ITag2nameService;
import com.asimplefox.service.ITagsService;
import com.asimplefox.service.IVidListService;
import com.asimplefox.service.abst.ResultU;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.github.kloping.judge.Judge;
import io.github.kloping.rand.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author github.kloping
 */
@RestController
@RequestMapping("/api/tags")
public class TagsController implements ResultU {
    public Map<String, String> tag2name =
            Map.of("hot", "热门",
                    "new", "最新",
                    "rec", "推荐",
                    "cto", "动漫"
            );

    @GetMapping("all")
    public Map<String, String> all() {
        Map<String, String> tag2nm = new HashMap<>();
        for (Tag2name name : tag2nameService.list()) {
            tag2nm.put(name.getTag(), name.getName());
        }
        tag2nm.putAll(tag2name);
        return tag2nm;
    }

    @Autowired
    ITag2nameService tag2nameService;

    @Autowired
    ITagsService tagsService;

    @DeleteMapping
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object delete(@RequestParam("id") List<Integer> id, @RequestParam("tag") String tag) {
        if (!all().containsKey(tag)) return result(400, "不存在该分类");
        int n = 0;
        for (Integer i : id) {
            QueryWrapper<Tags> qw = new QueryWrapper<>();
            qw.eq("vlid", i);
            qw.eq("tag", tag);
            n += tagsService.remove(qw) ? 1 : 0;
        }
        return n > 0 ? result(200, "移除生效", "num", n) : error("移除失败");
    }

    @PutMapping
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object put(@RequestParam("id") List<Integer> id, @RequestParam("tag") String tag) {
        if (!all().containsKey(tag)) return result(400, "不存在该分类");
        int n = 0;
        for (Integer i : id) {
            QueryWrapper<Tags> qw = new QueryWrapper<>();
            qw.eq("vlid", i);
            qw.eq("tag", tag);
            if (tagsService.getOne(qw) == null) tagsService.save(new Tags().setTag(tag).setVlid(i));
        }
        return result(200, "保存完成");
    }

    @Autowired
    IVidListService vidListService;

    @GetMapping
    public Object get(@RequestParam("tag") String tag) {
        if (!all().containsKey(tag)) return result(400, "不存在该分类");
        List<Tags> tags = tagsService.lambdaQuery().eq(Tags::getTag, tag).list();
        List<Integer> ids = tags.stream().map(Tags::getVlid).collect(Collectors.toList());
        if (ids.isEmpty()) return EMPTY_ARRAY;
        List<VidList> lists = vidListService.listByIds(ids);
        return (lists == null || lists.isEmpty()) ? EMPTY_ARRAY : lists;
    }

    @GetMapping("crt")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object crt(@RequestParam("tag") @Nullable String tag, @RequestParam("name") String name) {
        if (all().containsValue(name)) return error("分类已存在");
        if (all().containsKey(tag)) return error("分类已存在");
        Tag2name tag2name = new Tag2name();
        if (Judge.isNotEmpty(tag)) tag2name.setTag(tag);
        else tag2name.setTag(genTag());
        tag2name.setName(name);
        if (tag2nameService.save(tag2name)) {
            return result(200, "分类创建成功", "tag_id", tag2name.getTag());
        } else return fail("创建异常");
    }

    private String genTag() {
        while (true) {
            int r = RandomUtils.RANDOM.nextInt(122 - 97) + 97;
            int n = RandomUtils.RANDOM.nextInt(10);
            String t = String.valueOf((char) r) + n;
            if (!all().containsKey(t)) return t;
        }
    }

    @GetMapping("del")
    @PreAuthorize("hasAnyAuthority('admin','system')")
    public Object del(@RequestParam("tag") @Nullable String tag, @RequestParam("name") @Nullable String name) {
        if (tag == null && name == null) return fail("参数异常");
        boolean k = tag2nameService.lambdaUpdate().eq(Tag2name::getName, name).or().eq(Tag2name::getTag, tag).remove();
        if (k) {
            return success("分类删除成功");
        } else return fail("删除异常");
    }
}
